import { TIME_24, TIME_96 } from '@/pages/ETrade/components/helper';
import { CODE1, headerMap } from './helper';
export const getAllStation = (data) =>
  _.flattenDeep(data?.map((a) => a?.children?.map((b) => b.value)));

export const getTableData = (_data, _order, point, _selectKeys) => {
  const { data, meta } = _data || {};
  if (!_data || !data || !meta)
    return {
      tableData: [],
      exportTable: [],
    };
  const TIMELIST = point == '96' ? TIME_96 : TIME_24;
  // 数据处理
  const fmtDate = (v) => v.replace(/[-]/g, '');
  const fmtRow = (_row, _title, _tag, id) => {
    let res = {
      id: id + _.uniqueId(),
      [CODE1]: _tag === '时点' ? TIMELIST[_title - 1] : _tag === '日期' ? fmtDate(_title) : _title,
      tag: _tag,
    };
    meta.map((k, i) => {
      if (!_selectKeys.includes(headerMap[k])) return;
      let val = _row[i];
      const fixNum = headerMap[k].toLocaleLowerCase().includes('quantity') ? 3 : 2;
      val = parseFloat(val).toFixed(fixNum);
      res[headerMap[k]] = val;
    });

    return res;
  };
  // 递归种一颗树
  let exportTable = []; // 导出用
  const fn = ({ total, ...list }, title, lv, id = '') => {
    let result = fmtRow(total, title, _order[lv - 1], id);
    exportTable.push(result);
    let children = [];
    for (const k in list) {
      const temp = !!list[k]?.length
        ? fmtRow(list[k], k, _order[lv], result.id)
        : fn(list[k], k, lv + 1, result.id);
      children.push(temp);
      exportTable.push(temp);
    }
    if (!!children.length) {
      result.children = children.sort((a, b) => a[CODE1].localeCompare(b[CODE1], 'zh-CN'));
    }
    return result;
  };
  // 总合计要单独一行
  const { children, ...total } = fn(data, '合计', 0);
  const tableData = [total, ...(children || [])];
  return { tableData, exportTable };
};

export const flattenDeep = (list = []) => {
  const selectedKeys = [];
  list?.forEach((l) => {
    // 默认选中
    if (l?.checkbox === 1 && l?.key) {
      selectedKeys.push(l.key);
    }
    l?.children?.length && selectedKeys.push(...flattenDeep(l.children, selectedKeys));
  });
  return selectedKeys;
};

// 处理排序数据
export const removeEmptyRowData = (dataSource, name) => {
  const sortData = [];
  const noSortData = [];

  dataSource.map((item) => {
    if (item[name] || item[name] == 0) {
      sortData.push(item);
    } else {
      noSortData.push(item);
    }
  });
  return {
    noSortData,
    sortData,
  };
};
